<template>
	<view class="container">
		<!-- 登录表单 -->
		<view class="form-container" v-show="isLogin">
			<view class="input-group">
				<input type="text" v-model="loginForm.username" class="input-field" placeholder="用户名"
					placeholder-style="color: #ccc;" />
			</view>
			<view class="input-group">
				<input type="password" v-model="loginForm.password" class="input-field" placeholder="密码"
					placeholder-style="color: #ccc;" />
			</view>
			<button class="submit-btn" @click="login">登录</button>
			<view class="switch-tip">
				<text>没有账号？</text>
				<text class="switch-link" @click="toggleForm">去注册</text>
			</view>
		</view>

		<!-- 注册表单 -->
		<view class="form-container" v-show="!isLogin">
			<view class="input-group">
				<input type="text" v-model="registerForm.username" class="input-field" placeholder="用户名"
					placeholder-style="color: #ccc;" @input="validateUsernameInput" />
				<text class="error-tip" v-if="errors.username">{{ errors.username }}</text>
			</view>
			<view class="input-group">
				<input type="password" v-model="registerForm.password" class="input-field" placeholder="密码"
					placeholder-style="color: #ccc;" @input="validatePasswordInput" />
				<text class="error-tip" v-if="errors.password">{{ errors.password }}</text>
			</view>
			<button class="submit-btn" @click="register">注册</button>
			<view class="switch-tip">
				<text>已有账号？</text>
				<text class="switch-link" @click="toggleForm">去登录</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, nextTick } from 'vue';

	// 响应式状态定义
	const isLogin = ref(true);

	// 登录表单数据
	const loginForm = ref({
		username: '',
		password: ''
	});

	// 注册表单数据
	const registerForm = ref({
		username: '',
		password: ''
	});

	// 错误提示信息
	const errors = ref({
		username: '',
		password: ''
	});

	// 切换登录和注册表单
	const toggleForm = () => {
		isLogin.value = !isLogin.value;
	};

	// 验证用户名
	const validateUsername = (username) => {
		const usernameRegex = /^[a-zA-Z0-9_]{5,8}$/;
		if (!username) return '';
		if (!usernameRegex.test(username)) {
			return '账号长度为5~8位，只能由数字、字母、下划线组成';
		}
		return '';
	};

	// 输入时验证用户名
	const validateUsernameInput = () => {
		const usernameError = validateUsername(registerForm.value.username);
		errors.value.username = usernameError;
	};

	// 验证密码
	const validatePassword = (password) => {
		const passwordRegex = /^[a-zA-Z0-9_]{5,12}$/;
		if (!password) return '';
		if (!passwordRegex.test(password)) {
			return '密码长度为5~12位，只能由数字、字母、下划线组成';
		}
		return '';
	};

	// 输入时验证密码
	const validatePasswordInput = () => {
		const passwordError = validatePassword(registerForm.value.password);
		errors.value.password = passwordError;
	};

	// 登录方法
const login = () => {
  const { username, password } = loginForm.value;

  if (!username || !password) {
    uni.showToast({
      title: '请输入账号和密码',
      icon: 'none'
    });
    return;
  }

  uni.request({
    url: 'http://localhost:8080/user/login',
    method: 'POST',
    header: {
      'content-type': 'application/json'
    },
    data: {
      username,
      password
    },
    success: (res) => {
      console.log('登录响应:', res);
      if (res.statusCode === 200 && res.data.status === 200) {
        const token = res.data.body.token;
        const nickname = username;

        // 使用同步存储确保数据写入完成
        try {
          uni.setStorageSync('token', token);
          uni.setStorageSync('nickname', nickname);
          console.log('✅ 数据存储完成');
        } catch (e) {
          console.error('❌ 数据存储失败:', e);
        }

        uni.showToast({
          title: '登录成功',
          icon: 'success'
        });

        // 直接跳转，依赖目标页面的onShow检查
        setTimeout(() => {
          console.log('🔄 跳转到我的页面');
          uni.switchTab({
            url: "/pages/mine/mine",
            success: () => {
              console.log('✅ 页面跳转成功');
            }
          });
        }, 1000); // 确保Toast显示完成
      } else {
        uni.showToast({
          title: res.data?.description || '登录失败',
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      console.error('登录请求失败:', err);
      uni.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    }
  });
};

	// 注册方法
	const register = () => {
		const {
			username,
			password
		} = registerForm.value;

		// 重置错误信息
		errors.value = {
			username: '',
			password: ''
		};

		// 检查是否为空
		if (!username) {
			errors.value.username = '请输入用户名';
			return;
		}
		if (!password) {
			errors.value.password = '请输入密码';
			return;
		}

		// 验证用户名
		const usernameError = validateUsername(username);
		if (usernameError) {
			errors.value.username = usernameError;
			return;
		}

		// 验证密码
		const passwordError = validatePassword(password);
		if (passwordError) {
			errors.value.password = passwordError;
			return;
		}

		// 调用注册接口
		uni.request({
			url: 'http://localhost:8080/user/registered',
			method: 'POST',
			header: {
				'content-type': 'application/json'
			},
			data: {
				username: username,
				password: password
			},
			success: (res) => {
				console.log('注册响应:', res);
				if (res.statusCode === 200 && res.data && res.data.status === 200) {
					uni.showToast({
						title: res.data.description || '注册成功',
						icon: 'success'
					});

					setTimeout(() => {
						isLogin.value = true;
						loginForm.value.username = username;
						loginForm.value.password = '';
					}, 1500);
				} else {
					uni.showToast({
						title: res.data?.description || '注册失败',
						icon: 'none'
					});
				}
			},
			fail: (err) => {
				console.error('注册请求失败:', err);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			}
		});
	};
</script>

<style scoped>
	.container {
		width: 100%;
		min-height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 40rpx;
		box-sizing: border-box;
		background-color: #fff;
	}

	.form-container {
		width: 100%;
		max-width: 600rpx;
		padding: 40rpx 0;
	}

	.input-group {
		margin-bottom: 40rpx;
		width: 100%;
		position: relative;
	}

	.input-field {
		width: 100%;
		height: 90rpx;
		border-radius: 45rpx;
		background-color: #f8f8f8;
		border: 2rpx solid #e0e0e0;
		padding: 0 30rpx;
		box-sizing: border-box;
		font-size: 32rpx;
		color: #333;
	}

	.input-field:focus {
		outline: none;
		border-color: #00a16c;
		background-color: #f0f0f0;
	}

	.submit-btn {
		width: 100%;
		height: 90rpx;
		background-color: #00a16c;
		color: #fff;
		border: none;
		border-radius: 45rpx;
		font-size: 36rpx;
		font-weight: bold;
		margin-top: 20rpx;
	}

	.submit-btn:active {
		background-color: #008a5a;
	}

	.switch-tip {
		margin-top: 40rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
		color: #666;
	}

	.switch-link {
		color: #007aff;
		margin-left: 10rpx;
		text-decoration: none;
		background-color: gainsboro;
		padding: 5rpx 10rpx;
		border-radius: 10rpx;
	}

	.error-tip {
		display: block;
		font-size: 24rpx;
		color: #ff0000;
		margin-top: 10rpx;
		padding-left: 20rpx;
	}
</style>